package org.misalen.web.admin.controllers;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.misalen.web.admin.util.ServerResult;
import org.misalen.web.service.file.InfoType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/upload")
public class UploadController extends BaseController {

	@RequestMapping(value = "/image", method = { RequestMethod.POST })
	public @ResponseBody ServerResult image(MultipartFile file) throws Exception {
		String url = ossFile.uploadFile(file.getInputStream(),
				UUID.randomUUID() + getExtensionName(file.getOriginalFilename()), InfoType.imageCode);
		return renderSuccess(url);
	}

	@RequestMapping(value = "/video", method = { RequestMethod.POST })
	public @ResponseBody ServerResult video(MultipartFile file) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		InputStream inputStream = file.getInputStream();
		map.put("size", inputStream.available());
		map.put("time", 10000);
		String url = ossFile.uploadFile(file.getInputStream(),
				UUID.randomUUID() + getExtensionName(file.getOriginalFilename()), InfoType.vedioCode);
		map.put("url", url);
		return renderSuccess(map);
	}

	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return "." + filename.substring(dot + 1);
			}
		}
		return "." + filename;
	}
}
